﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using ReservoirBLL;
using ReservoirModel;

namespace ReservoirManger
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //防止页面刷新后页面上的数据消失
            this.txtName.Attributes["value"] = txtName.Text;
            this.txtPwd.Attributes["value"] = txtPwd.Text;
        }
        /// <summary>
        /// 登录功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //实例化类对象
            LoginBLL loginBLL = new LoginBLL();
            //从前台获取用户输入的数据
            string UserName = txtName.Text;
            string PassWord = txtPwd.Text;

            //获取验证码
            string Code = Session["image"].ToString().Trim();
            string Captcha = this.txtCaptcha.Text.ToString().Trim();
            //判断用户输入的验证码是否正确
            if (Code != Captcha.ToUpper())
            {
                Response.Write("<script>alert('验证码错误！');</script>");
                txtCaptcha.Text = "";
            }
            else
            {
                //验证码正确  判断账号密码是否正确
                TBUser user = loginBLL.Login(UserName, PassWord);
                //保存用户资料
                IdentityManager.SaveUser(user);
                if (user == null)
                {
                    //登录成功                         
                    Response.Write("<script>alert('用户名或密码错误！');</script>");
                    txtCaptcha.Text = "";
                }
                else
                {
                    Response.Write("<script>alert('登录成功！');window.location.href='Default.aspx';</script>");
                }
                //int result = loginBLL.Login(UserName, PassWord);
                //if (result > 0)
                //{
                //    //登录成功  声明变量接收当前ID
                //    ReservoirConn con = new ReservoirConn();
                //    var list = (from u in con.TBUser
                //                where u.Name == UserName
                //                select new
                //                {
                //                    ID = u.Id,
                //                }).ToList()[0].ID;
                //    //Server.UrlEncode对中文进行编码，解决乱码问题
                //    //把当前用户名和ID保存在Cookie中
                //    HttpCookie cookie = new HttpCookie("Name", Server.UrlEncode(UserName));
                //    HttpCookie cookie2 = new HttpCookie("ID", (list).ToString());
                //    Response.Cookies.Add(cookie);
                //    Response.Cookies.Add(cookie2);
                //    //保存身份验证票据
                //    FormsAuthentication.SetAuthCookie(UserName, false);
            }
        }
    }
}